#include <stack>
#include <algorithm>

using namespace std;

class Solution {
public:
    int longestValidParentheses(string s) {
        int ans = 0;
        stack<int> sta({ -1 });
        for (int i = 0; i < s.length(); ++i) {
            if (s[i] == '(') {
                sta.emplace(i);
            }
            else {
                sta.pop();
                if (sta.empty()) {
                    sta.emplace(i);
                }
                else {
                    ans = max(ans, i - sta.top());
                }
            }
        }
        return ans;
    }
};
